﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SynoManager.GUI;

namespace SynoManager.DownloadStation.Plugins
{
    public partial class CredentialManagerPanel : PreferencesPanel
    {
        private readonly CredentialManager manager;

        public CredentialManagerPanel()
        {
            InitializeComponent();
        }

        public CredentialManagerPanel(CredentialManager manager)
            :this()
        {
            this.manager = manager;

            foreach(SiteCredential credential in manager.Credentials)
            {
                AddToList(credential);
            }
        }

        private void addToolStripButton_Click(object sender, EventArgs e)
        {
            CredentialForm form = new CredentialForm();
            DialogResult result = form.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                SiteCredential credential = form.Credentials;
                manager.Add(credential);
                AddToList(credential);
            }
        }

        private void AddToList(SiteCredential credential)
        {
            ListViewItem lvi = listView.Items.Add(credential.Host);
            lvi.SubItems.Add(credential.Username);
            lvi.Tag = credential;
        }

        private void editToolStripButton_Click(object sender, EventArgs e)
        {
            if (listView.SelectedItems.Count != 1)
                return;

            ListViewItem lvi = listView.SelectedItems[0];
            SiteCredential credential = (SiteCredential) lvi.Tag;

            CredentialForm form = new CredentialForm();
            form.Credentials = credential;

            DialogResult result = form.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                lvi.SubItems[0].Text = credential.Host;
                lvi.SubItems[1].Text = credential.Username;
            }
        }

        private void deleteToolStripButton_Click(object sender, EventArgs e)
        {
            if (listView.SelectedItems.Count != 1)
                return;

            ListViewItem lvi = listView.SelectedItems[0];
            SiteCredential credential = (SiteCredential)lvi.Tag;
            manager.Remove(credential);
            lvi.Remove();
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            editToolStripButton.Enabled = deleteToolStripButton.Enabled = listView.SelectedItems.Count == 1;
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            editToolStripButton_Click(sender, e);
        }

        public override void Save()
        {
            manager.Save();
            base.Save();
        }
    }
}
